<?php
define("PROVIDERSCLASS", "App\\Tagserver\\");
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
use App\Models\Configuration;
use App\Models\Defines\DefinesTranslation;
use App\Models\ColumnTranslation;
use Carbon\Carbon;
use App\Models\Article\ArticleTranslation as Article;

/**
**获取栏目
**/
function p($res,$id='',$data=[])
{
    if(empty($id)) return [];
    foreach($res as $item){
		if($item->pid == $id){
			
			$data[]=$item->column_mid;
 
			$pids = \Cache::remember('column_'. lang() .'_'.$id, env('SYSCACHETIME'), function() use($item) {
			  return  ColumnTranslation::select('id','sid','pid','column_mid')->lang()->where('pid',$item->sid)->get();
			});
			
			$them= p($pids,$item->sid);
			  
			if(count($them)){
                foreach($them as $v){if($v) $data[]=$v; }
			}				 
		}elseif($item->sid == $id){
			
			$data[]=$item->column_mid;
			
			$pids = \Cache::remember('sub_column_'. lang() .'_'.$id, env('SYSCACHETIME'), function() use($item) {
			  return  ColumnTranslation::select('id','sid','pid','column_mid')->lang()->where('pid',$item->sid)->get();
			});
			
			$them= p($pids,$item->sid);
		}
	}
 
   return $data;
}


/**
**找出父类
**/
function t($column)
{
	if($column->pid == 0) return $column->sid;
	//默认分类ID
	$pid=$column->pid;
	$columnid=$column->column_mid;
	$id=$column->id;
	$sid=$column->sid;
	$row = Cache::remember(lang().'_topClass_'.$column->column_mid, webconfig('SYSCACHETIME') , function() use($column){	 
		return ColumnTranslation::field()->lang()->where('sid',$column->sid)->first(); 
		 
	});
	while($row['pid']>0){
		$row = Cache::remember(lang().'_topClass_while_'.$row->column_mid, webconfig('SYSCACHETIME') , function() use($row){
			return ColumnTranslation::field()->where(['locale'=>lang(),'sid'=>$row->pid])->first();	 
		});
		 $pid = $row->pid;
		 $columnid= $row->column_mid;
		 $id= $row->id;
		 $sid= $row->sid;
	}
	return $sid;
}
/**
*获取上一条 文章、案例、产品
*/
function up($model)
{
		$routeName = request()->route()->getName();
		$slug = request()->route('slug');
		//当前缓存时间
		$tagcachetime=webconfig('SYSCACHETIME')/60;
		return $row = Cache::remember($routeName.'_up_'.$slug,$tagcachetime , function() use($model,$routeName,$slug){
			return $Article = $model::with('column')->lang()->where("slug", "<", $slug)->orderBy('id', 'desc')->first();
		});
}
 
/**
*获取下一条: 文章、案例、产品
*/
function down($model)
{
		$routeName = request()->route()->getName();
		$slug = request()->route("slug");
		//当前缓存时间
		$tagcachetime=webconfig('SYSCACHETIME')/60;
		return $row = Cache::remember($routeName.'_down_'.$slug,$tagcachetime , function() use($model,$routeName,$slug){
			return $Article = $model::with('column')->lang()->where('slug', '>', $slug)->orderBy('id', 'desc')->first();
		});
}
 
//面包屑导航
if (!function_exists('crumb')) {
	function crumb($catid){
		$row = ColumnTranslation::where(['locale'=>'zh','sid'=>$catid])->first();
		$tree[] = $row;
		while($row['pid']>0){
			 $row = ColumnTranslation::where(['locale'=>lang(),'sid'=>$row->pid])->first();
			 $tree[] = $row;
		}
		return array_reverse($tree);
	} 
}
 
/**获取配置值
 * @author pangxianfei <421339244@qq.com>
 */
if (!function_exists('webconfig')) {
    function webconfig($name)
    {
		$cacheName=config('app.name').'_db_'. lang() .'_'.$name;
		$cacheTime = env('SYSCACHETIME');
		if (Cache::has($cacheName)) {
			return Cache::get($cacheName); 
		}
		$config = Configuration::where('key', $name)->first();
		$value = $config->val ?? null;
		Cache::put($cacheName, $value,$cacheTime);
		 
        return $value;
    }
}


/**获取配置值 public 前台使用
 * @author pangxianfei <421339244@qq.com>
 */
if (!function_exists('siteconfig')) {
    function siteconfig($name)
    {
        $value = null;
		$cacheName=config('app.name').'_site_'. lang() .'_'.$name;
		if (Cache::has($cacheName)) {
			return Cache::get($cacheName); 
		}
		$config = DefinesTranslation::select("value")->lang()->where('keys', $name)->first();
		$value = $config->value?htmlspecialchars_decode($config->value):null;

		$cacheTime = env('SYSCACHETIME');
		Cache::put($cacheName, $value, $cacheTime);
        empty($cacheTime)?Cache::forever($cacheName, $value):Cache::put($cacheName, $value, $cacheTime);
        return Cache::get($cacheName);
    }
}


/**获取配置值
 * @author pangxianfei <421339244@qq.com>
 */
if (!function_exists('webconfigGroup')) {
    function webconfigGroup($ids)
    {
		$keyconfig = 'webconfig_group_'.lang()."_".$ids;
        if (empty(Cache::get($keyconfig))) {
            $config = Configuration::where('group_id', $ids)->get();
            
            Cache::put($keyconfig, $config, 3600);
        }
        return Cache::get($keyconfig);
    }
}
 






function setCacheKey($object=''){
		$page =1;
		$sysTagcachekey= request()->route()->getName();
	 
		$sysTagcachekey .= $object->id;
		$sysTagcachekey .= $object->column_mid;
		$sysTagcachekey .= $object->locale;
		$sysTagcachekey .= $object->model;
		
		foreach(request()->all() as $k=>$v){ 
		  $sysTagcachekey .=(string)$v;
		} 
	    return md5($sysTagcachekey);
	 
}

 
if (!function_exists('getDirectoryName')) {
function getDirectoryName($path=null){
		//$cachekey="tagServiceProvider_key";
		$path = $path??app_path('Tagserver');
		$files=[];
		if(!is_dir($path)) return $files;
		$dir = scandir($path);
		foreach ($dir as $value){
			$sub_path =$path .'/'.$value;
			if($value == '.' || $value == '..'){
				continue;
			}else if(is_dir($sub_path)){
				getDirectoryName($sub_path);
			}else{
				$filename = PROVIDERSCLASS.$value;
				$extension = @pathinfo($filename, PATHINFO_EXTENSION);
				if($extension =="php"){
					$filename = str_replace(strrchr($filename, "."),"",$filename);
					$files[]=$filename;
					 
				}
			}
		}
	  return $files;
	}
}

if (!function_exists('getFileTypeList')) {
    /**
     * 获取指定格式的文件
     * @param array $array
     * @param array $format
     * @return array
     */
    function getFileTypeList($array = [], $format = []) {
        $return = [];
        if (empty($array) || empty($format)) return $return;
        foreach ($array as $key => $value) {
            $arr = pathinfo($value);
            if (!empty($arr['extension']) && in_array($arr['extension'], $format)) $return[] = $value;
        }
        return $return;
    }
}




/**
 * 生成随机位数
 * @param  integer $len 长度
 * @return string
 */
if (!function_exists('makeRand')) {
	function makeRand($len = 6, $string = false)
	{
		if ($string) {
			$seed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
		} else {
			$seed = '0123456789';
		}
		return substr(str_shuffle(str_repeat($seed, $len)), 0, $len);
	}
}	
	
 
/**
* 获取文章内图片url
* @author pangxianfei <421339244@qq.com>
*/
if (!function_exists('getContentPicture')) {
	function getContentPicture($content,$number='all'){
		$html_string = htmlspecialchars_decode($content);
		$pattern = "/<[img|IMG].*?src=[\\'|\"](.*?(?:[\\.gif|\\.jpg|\\.png]))[\\'|\"].*?[\\/]?>/";
		preg_match_all($pattern, $html_string, $match);
	 
		if(isset($match[1])&&!empty($match[1])){
			if($number==='all'){
				return $match[1];
			}
			if(is_numeric($number)&&isset($match[1][$number])){
				return $match[1][$number];
			}
		}
		return [];
	}
}


/**
 * @author pangxianfei <421339244@qq.com>
 */
if (!function_exists('split')) {

    function split($expressions = null)
    {
        if(empty($expressions)) return null;

        list($field,$value) = explode('=',$expressions);

        if($field == "field"){
            $field = explode(',',$value);
            $count = count($field);
            $value = null;
            foreach($field as $key=>$item){
              if($key == $count-1) $value .= "'". $item ."'"; else $value .= "'". $item ."',";
            }
        }
        return $value;
    }
}


/**获取当前语言标志 后台使用
 * @author pangxianfei <421339244@qq.com>
 */
if (!function_exists('lang')) {
    function lang()
    {
        return app()->getLocale();
    }
}

/**获取当前语言标志 前台使用
 * @author pangxianfei <421339244@qq.com>
 */
if (!function_exists('language')) {
    function language()
    {
        return session()->get('language');
    }
}




/*推送百度收录
 *
 */
if (!function_exists('pushBaidu')) {
    function pushBaidu($urls = [])
    {
        if ($urls == null) return '';
        $ch = curl_init();
        $options = array(
            CURLOPT_URL => webconfig('zz_baidu'),
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        return $result = curl_exec($ch);
    }
}
/*
奇数
*/
if (!function_exists('isEven')) {
    function isEven($num)
    {
        return (is_numeric($num) & (!($num & 1)));
    }
}

if (!function_exists('randno')) {
    function randno(){
        while (true) {
            $them = date("s").rand(1,99);
            $no = str_replace('.','',substr(microtime(true),-10));
            if (! \DB::table('randno')->where('no', $no)->count()) {
                 \DB::table('randno')->insert(['no'=>$no]);
                 return $no;
            }
        }         
    }
}
 

/**
 * 截取中文字符串
 * @param string $string 中文字符串
 * @param int $sublen 截取长度
 * @param int $start 开始长度 默认0
 * @param string $code 编码方式 默认UTF-8
 * @param string $omitted 末尾省略符 默认...
 * @return string
 */
if (!function_exists('cutstr')) {
    function cutstr($string, $sublen = 250, $omitted = '', $start = 0, $code = 'UTF-8')
    {
        $string = strip_tags($string);
        $length = \Str::length($string);
        $string = str_replace("　", "", $string);
        $string = mb_strcut($string, $start, $sublen, $code);
        $string .= $length>$sublen?$omitted:'';
        return $string;
    }
}

/**
 * 判断当前url是否被选中
 * @author pangxianfei <421339244@qq.com>
 */
if (!function_exists('getActivated')) {
    function getActivated($url,$activated = 'cur')
    {
        $urlActiveStatus = '';
        if (!empty($url)) {
            $requestUri = $_SERVER['REQUEST_URI'];
            $getUrl = url()->current();
            if ($getUrl == $url) {
                $urlActiveStatus = $activated;
            }
        }
        return $urlActiveStatus;
    }
}

/**
 * 返回当前域名
 * @author pangxianfei <421339244@qq.com>
 */
if (!function_exists('http_host')) {
    function http_host()
    {
        return dirname(url()->current());
    }
}

/*
*写入配置
 *         $data = [
            'DDDDDDDD' => 'file',
            'DDDDDDDD' => 'ddd'
           ];
        return myEnv($data);
*/
if (!function_exists('sysEnv')) {
    function sysEnv(array $data)
    {
        if (!$data) return;
        $envPath = base_path() . DIRECTORY_SEPARATOR . '.env';
		$envfilename=time();
		@copy($envPath,storage_path()."/config/".$envfilename.".env");
		
        $contentArray = collect(file($envPath, FILE_IGNORE_NEW_LINES));
        $contentArray->transform(function ($item) use ($data) {
            foreach ($data as $key => $value) {
                if (str_contains($item, $key)) {
                   return $key . '=' . $value;
                }
            }
            return $item;
        });
		
		
        foreach ($contentArray->toArray() as $key=>$item) {
            
			 $str = explode("=", $item);
			 
            if (array_key_exists($str[0], $data)) {
				
				 if(count($str)>2){
					foreach($str as $subkey=>$som){
                        $str[1] .= $subkey >1 ?$som:'';
					}						
				 }
				  $contentArray[$key]=$str[0] . '=' . $str[1];

                  unset($data[$str[0]]);
				  //print_r($str[0].'='.$str[1]);echo '<br>';
            } 
        }
	 
        foreach ($data as $key => $value) {
            $contentArray[] = $key . '=' . $value;
        }
        $content = implode("\n", $contentArray->toArray());
        \File::put($envPath, $content);
    }
}
 

/**
 * 判断是否为手机端
 * @author pangxianfei <421339244@qq.com>
 */

if (!function_exists('isMobile')) {
    function isMobile()
    {
        if (isset ($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array('nokia', 'sony', 'ericsson', 'mot','samsung', 'htc', 'sgh', 'lg', 'sharp',
                'sie-', 'philips', 'panasonic', 'alcatel','meizu', 'android', 'netfront', 'symbian',
                'ucweb', 'windowsce', 'palm', 'operamini','operamobi', 'openwave', 'nexusone', 'cldc','midp', 'wap', 'mobile'
            );
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                $result = true;
            } else {
                $result = false;
            }
        } else {
            $result = false;
        }
        return $result;
    }
}

/**
 * 获取 模块 控制器 方法名
 */
if (!function_exists('getTemplatePath')) {
    function getTemplatePath()
    {
        list($class, $method) = explode('@', \Route::current()->getActionName());
        # 模块名
        $modules = str_replace(
            '\\',
            '.',
            str_replace(
                'App\\Http\\Controllers\\',
                '',
                trim(
                    implode('\\', array_slice(explode('\\', $class), 0, -1)),
                    '\\'
                )
            )
        );
        # 控制器名称
        $Controller = str_replace(
            'Controller',
            '',
            substr(strrchr($class, '\\'), 1)
        );
        # 方法名
        $method = $method;
        return ['modules'=>$modules,'Controller'=>$Controller,'method'=>$method];
    }
}



/**获取当前控制器与方法
 * @return array
 */
if (!function_exists('getCurrentAction')) {
    function getCurrentAction()
    {
        $action = \Route::current()->getActionName();
        list($class, $method) = explode('@', $action);
        $class = substr(strrchr($class, '\\'), 1);
        return ['controller' => $class, 'method' => $method];
    }
}

/**获取当前控制器名
 * @return mixed
 */
if (!function_exists('getCurrentControllerName')) {
    function getCurrentControllerName()
    {
        return getCurrentAction()['controller'];
    }
}
/**获取当前方法名
 * @return mixed
 */
if (!function_exists('getCurrentMethodName')) {
    function getCurrentMethodName()
    {
        return getCurrentAction()['method'];
    }
}

//日期格式化
if (!function_exists('format')) {
    function format($data, $type = 'Y-m-d')
    {
        $data = is_int($data) ? $data : strtotime($data);
        if (empty($type)) $type = 'Y.m';
        return \Carbon\Carbon::parse($data)->format($type);
    }
}

/*
*验证邮箱
*/
if (!function_exists('isEmail')) {
	function isEmail($email)
	{
		$pattern = "/^[^_][\\w]*@[\\w.]+[\\w]*[^_]\$/";
		if (preg_match($pattern, $email, $matches)) {
			return true;
		}
		return false;
	}
}
/** 
 * 判断手机号码是否合法 
 * @param $mobile 手机号码 
 * @return bool 
 */
if (!function_exists('checkMobile')) {
	function checkMobile($mobile)
	{
		$pattern = '/^(0|86|17951)?(888|13[0-9]|15[012356789]|17[0-9]|111|18[0-9]|14[57])[0-9]{8}$/';
		if (preg_match($pattern, $mobile)) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
}
/** 
 * 判断真实姓名是否合法 
 * @param $realname 
 * @return bool 
 */
if (!function_exists('checkMobile')) {
	function checkUserName($realname)
	{
		$patten = '/^[\\x{4e00}-\\x{9fa5}]+$/u';
		if (preg_match($patten, $realname)) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
}
/***
*xss过滤
****/
if (!function_exists('clssXss')) {
	function clssXss(&$string, $low = False)
	{
		if (!is_array($string)) {
			$string = trim($string);
			$string = strip_tags($string);
			$string = htmlspecialchars($string);
			if ($low) {
				return True;
			}
			$string = str_replace(array('"', "\\", "'", "/", "..", "../", "./", "//"), '', $string);
			$no = '/%0[0-8bcef]/';
			$string = preg_replace($no, '', $string);
			$no = '/%1[0-9a-f]/';
			$string = preg_replace($no, '', $string);
			$no = '/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]+/S';
			$string = preg_replace($no, '', $string);
			return True;
		}
		$keys = array_keys($string);
		foreach ($keys as $key) {
			clssXss($string[$key]);
		}
	}
}

/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串，并对字符串做urlencode编码
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
function createLinkString($para)
{
    $arg = "";
    while (list($key, $val) = each($para)) {
        $arg .= $key . "=" . urlencode($val) . "&";
    }
    //去掉最后一个&字符
    $arg = substr($arg, 0, count($arg) - 2);
    //如果存在转义字符，那么去掉转义
    if (get_magic_quotes_gpc()) {
        $arg = stripslashes($arg);
    }
    return $arg;
}


//获取内容纯文本
if (!function_exists('getContentText')) {
	function getContentText($str)
	{
		$str = preg_replace("/<style .*?<\\/style>/is", "", $str);
		$str = preg_replace("/<script .*?<\\/script>/is", "", $str);
		$str = preg_replace("/<p .*?<\\/p>/is", "", $str);
		$str = preg_replace("/<br \\s*\\/>/i", "", $str);
		$str = preg_replace("/<\\/?p>/i", "", $str);
		$str = preg_replace("/<\\/?td>/i", "", $str);
		$str = preg_replace("/<\\/?div>/i", "", $str);
		$str = preg_replace("/<\\/?ul>/i", "", $str);
		$str = preg_replace("/<\\/?span>/i", "", $str);
		$str = preg_replace("/<\\/?li>/i", "", $str);
		$str = preg_replace("/ /i", " ", $str);
		$str = preg_replace("/ /i", " ", $str);
		$str = preg_replace("/&/i", "&", $str);
		$str = preg_replace("/&/i", "&", $str);
		$str = preg_replace("/</i", "<", $str);
		$str = preg_replace("/</i", "<", $str);
		$str = preg_replace("/“/i", '"', $str);
		$str = preg_replace("/&ldquo/i", '"', $str);
		$str = preg_replace("/‘/i", "'", $str);
		$str = preg_replace("/&lsquo/i", "'", $str);
		$str = preg_replace("/'/i", "'", $str);
		$str = preg_replace("/&rsquo/i", "'", $str);
		$str = preg_replace("/>/i", ">", $str);
		$str = preg_replace("/>/i", ">", $str);
		$str = preg_replace("/”/i", '"', $str);
		$str = preg_replace("/&rdquo/i", '"', $str);
		$str = strip_tags($str);
		$str = html_entity_decode($str, ENT_QUOTES, "utf-8");
		$str = preg_replace("/&#.*?;/i", "", $str);
		return $str;
	}

}



if (!function_exists('listToTree')) {
	function listToTree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
		$tree = array();
		if (is_array($list)) {
			$refer = array();
			foreach ($list as $key => $data) {
				$refer[$data[$pk]] = &$list[$key];
			}

			foreach ($list as $key => $data) {
				// 判断是否存在parent
				$parentId = $data[$pid];

				if ($root == $parentId) {
					$tree[$data[$pk]] = &$list[$key];
				} else {
					if (isset($refer[$parentId])) {
						$parent = &$refer[$parentId];
						$parent[$child][$data[$pk]] = &$list[$key];
					}
				}
			}
		}

		return $tree;
	}
}

//获取上一页的URL
if (!function_exists('getPreUrl')) {
	function getPreUrl() {
		return url()->previous();
	}
}


//手机号码 中间4位加密
if (!function_exists('get_encryption_mobile')) {
	function get_encryption_mobile($tel) {
		$new_tel = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $tel);
		return $new_tel;
	}
}
 

//随机验证码
if (!function_exists('random_verification_code')) {
    function randomCode($length = 6) {
        $code = '';
        for ($i = 0; $i < $length; $i++) $code .= mt_rand(0, 9);
        return $code;
    }
}



    /**
     * 取两坐标距离
     *
     * @param float $lng1 经度1
     * @param float $lat1 纬度1
     * @param float $lng2 经度2
     * @param float $lat2 纬度2
     *
     * @return float
     */
if (!function_exists('getDistance')) {
    function getDistance(float $lng1, float $lat1, float $lng2, float $lat2): float
    {
        $radLat1 = deg2rad($lat1);
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
     
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
     
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
         
        return $s;
	}
}


/**
     * get请求
     *
     * @param string $url URL地址
     * @param string $header header头
     *
     * @return mixed
     */
    function get(string $url, $header = null)
    {
        $ch = curl_init();

        if(isset($header))
        {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * Post请求
     *
     * @param string $url URL地址
     * @param string $param 参数
     * @param string $dataType 数据类型
     *
     * @return mixed
     */
    function post(string $url, $param = '', string $dataType = 'form')
    {
        $dataTypeArr = [
            'form' => ['content-type: application/x-www-form-urlencoded;charset=UTF-8'],
            'json' => ['Content-Type: application/json;charset=utf-8'],
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $dataTypeArr[$dataType]);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $result = curl_exec($ch);
        curl_close($ch);
        $result = trim($result, "\xEF\xBB\xBF");
        return $result;
}




  /**
     * 文件打包下载
     * @param string $downloadZip 打包后下载的文件名
     * @param array $list 打包文件组
     * @return void
     */
    function addZip(string $downloadZip, array $list)
    {
        // 初始化Zip并打开
        $zip = new \ZipArchive();

        // 初始化
        $bool = $zip->open($downloadZip, \ZipArchive::CREATE|\ZipArchive::OVERWRITE);

        if($bool === TRUE)
        {
            foreach ($list as $key => $val) 
            {
                // 把文件追加到Zip包并重命名  
                // $zip->addFile($val[0]);
                // $zip->renameName($val[0], $val[1]);
                // 把文件追加到Zip包
                $zip->addFile($val, basename($val));
            }
        }
        else
        {
            exit('ZipArchive打开失败，错误代码：' . $bool);
        }

        // 关闭Zip对象
        $zip->close();

        // 下载Zip包
        header('Cache-Control: max-age=0');
        header('Content-Description: File Transfer');            
        header('Content-disposition: attachment; filename=' . basename($downloadZip)); 
        header('Content-Type: application/zip');                     // zip格式的
        header('Content-Transfer-Encoding: binary');                 // 二进制文件
        header('Content-Length: ' . filesize($downloadZip));          // 文件大小
        readfile($downloadZip);

        exit();
}


 function delFile($path){
	$url=iconv('utf-8','gbk',$path);
	if(PATH_SEPARATOR == ':'){ //linux
		@unlink($path);
	}else{  //Windows
		@unlink($url);
	}
	return true;
}

/**
     * @param 生成随机得昵称
     * @param
     * @return 昵称
*/
if (!function_exists('randName')) {
   function randName(){
        $nicheng_tou=array('快乐的','冷静的','醉熏的','潇洒的','糊涂的','积极的','冷酷的','深情的','粗暴的','温柔的','可爱的','愉快的','义气的','认真的','威武的','帅气的','传统的','潇洒的','漂亮的','自然的','专一的','听话的','昏睡的','狂野的','等待的','搞怪的','幽默的','魁梧的','活泼的','开心的','高兴的','超帅的','留胡子的','坦率的','直率的','轻松的','痴情的','完美的','精明的','无聊的','有魅力的','丰富的','繁荣的','饱满的','炙热的','暴躁的','碧蓝的','俊逸的','英勇的','健忘的','故意的','无心的','土豪的','朴实的','兴奋的','幸福的','淡定的','不安的','阔达的','孤独的','独特的','疯狂的','时尚的','落后的','风趣的','忧伤的','大胆的','爱笑的','矮小的','健康的','合适的','玩命的','沉默的','斯文的','香蕉','苹果','鲤鱼','鳗鱼','任性的','细心的','粗心的','大意的','甜甜的','酷酷的','健壮的','英俊的','霸气的','阳光的','默默的','大力的','孝顺的','忧虑的','着急的','紧张的','善良的','凶狠的','害怕的','重要的','危机的','欢喜的','欣慰的','满意的','跳跃的','诚心的','称心的','如意的','怡然的','娇气的','无奈的','无语的','激动的','愤怒的','美好的','感动的','激情的','激昂的','震动的','虚拟的','超级的','寒冷的','精明的','明理的','犹豫的','忧郁的','寂寞的','奋斗的','勤奋的','现代的','过时的','稳重的','热情的','含蓄的','开放的','无辜的','多情的','纯真的','拉长的','热心的','从容的','体贴的','风中的','曾经的','追寻的','儒雅的','优雅的','开朗的','外向的','内向的','清爽的','文艺的','长情的','平常的','单身的','伶俐的','高大的','懦弱的','柔弱的','爱笑的','乐观的','耍酷的','酷炫的','神勇的','年轻的','唠叨的','瘦瘦的','无情的','包容的','顺心的','畅快的','舒适的','靓丽的','负责的','背后的','简单的','谦让的','彩色的','缥缈的','欢呼的','生动的','复杂的','慈祥的','仁爱的','魔幻的','虚幻的','淡然的','受伤的','雪白的','高高的','糟糕的','顺利的','闪闪的','羞涩的','缓慢的','迅速的','优秀的','聪明的','含糊的','俏皮的','淡淡的','坚强的','平淡的','欣喜的','能干的','灵巧的','友好的','机智的','机灵的','正直的','谨慎的','俭朴的','殷勤的','虚心的','辛勤的','自觉的','无私的','无限的','踏实的','老实的','现实的','可靠的','务实的','拼搏的','个性的','粗犷的','活力的','成就的','勤劳的','单纯的','落寞的','朴素的','悲凉的','忧心的','洁净的','清秀的','自由的','小巧的','单薄的','贪玩的','刻苦的','干净的','壮观的','和谐的','文静的','调皮的','害羞的','安详的','自信的','端庄的','坚定的','美满的','舒心的','温暖的','专注的','勤恳的','美丽的','腼腆的','优美的','甜美的','甜蜜的','整齐的','动人的','典雅的','尊敬的','舒服的','妩媚的','秀丽的','喜悦的','甜美的','彪壮的','强健的','大方的','俊秀的','聪慧的','迷人的','陶醉的','悦耳的','动听的','明亮的','结实的','魁梧的','标致的','清脆的','敏感的','光亮的','大气的','老迟到的','知性的','冷傲的','呆萌的','野性的','隐形的','笑点低的','微笑的','笨笨的','难过的','沉静的','火星上的','失眠的','安静的','纯情的','要减肥的','迷路的','烂漫的','哭泣的','贤惠的','苗条的','温婉的','发嗲的','会撒娇的','贪玩的','执着的','眯眯眼的','花痴的','想人陪的','眼睛大的','高贵的','傲娇的','心灵美的','爱撒娇的','细腻的','天真的','怕黑的','感性的','飘逸的','怕孤独的','忐忑的','高挑的','傻傻的','冷艳的','爱听歌的','还单身的','怕孤单的','懵懂的');
        $nicheng_wei=array('嚓茶','凉面','便当','毛豆','花生','可乐','灯泡','哈密瓜','野狼','背包','眼神','缘分','雪碧','人生','牛排','蚂蚁','飞鸟','灰狼','斑马','汉堡','悟空','巨人','绿茶','自行车','保温杯','大碗','墨镜','魔镜','煎饼','月饼','月亮','星星','芝麻','啤酒','玫瑰','大叔','小伙','哈密瓜，数据线','太阳','树叶','芹菜','黄蜂','蜜粉','蜜蜂','信封','西装','外套','裙子','大象','猫咪','母鸡','路灯','蓝天','白云','星月','彩虹','微笑','摩托','板栗','高山','大地','大树','电灯胆','砖头','楼房','水池','鸡翅','蜻蜓','红牛','咖啡','机器猫','枕头','大船','诺言','钢笔','刺猬','天空','飞机','大炮','冬天','洋葱','春天','夏天','秋天','冬日','航空','毛衣','豌豆','黑米','玉米','眼睛','老鼠','白羊','帅哥','美女','季节','鲜花','服饰','裙子','白开水','秀发','大山','火车','汽车','歌曲','舞蹈','老师','导师','方盒','大米','麦片','水杯','水壶','手套','鞋子','自行车','鼠标','手机','电脑','书本','奇迹','身影','香烟','夕阳','台灯','宝贝','未来','皮带','钥匙','心锁','故事','花瓣','滑板','画笔','画板','学姐','店员','电源','饼干','宝马','过客','大白','时光','石头','钻石','河马','犀牛','西牛','绿草','抽屉','柜子','往事','寒风','路人','橘子','耳机','鸵鸟','朋友','苗条','铅笔','钢笔','硬币','热狗','大侠','御姐','萝莉','毛巾','期待','盼望','白昼','黑夜','大门','黑裤','钢铁侠','哑铃','板凳','枫叶','荷花','乌龟','仙人掌','衬衫','大神','草丛','早晨','心情','茉莉','流沙','蜗牛','战斗机','冥王星','猎豹','棒球','篮球','乐曲','电话','网络','世界','中心','鱼','鸡','狗','老虎','鸭子','雨','羽毛','翅膀','外套','火','丝袜','书包','钢笔','冷风','八宝粥','烤鸡','大雁','音响','招牌','胡萝卜','冰棍','帽子','菠萝','蛋挞','香水','泥猴桃','吐司','溪流','黄豆','樱桃','小鸽子','小蝴蝶','爆米花','花卷','小鸭子','小海豚','日记本','小熊猫','小懒猪','小懒虫','荔枝','镜子','曲奇','金针菇','小松鼠','小虾米','酒窝','紫菜','金鱼','柚子','果汁','百褶裙','项链','帆布鞋','火龙果','奇异果','煎蛋','唇彩','小土豆','高跟鞋','戒指','雪糕','睫毛','铃铛','手链','香氛','红酒','月光','酸奶','银耳汤','咖啡豆','小蜜蜂','小蚂蚁','蜡烛','棉花糖','向日葵','水蜜桃','小蝴蝶','小刺猬','小丸子','指甲油','康乃馨','糖豆','薯片','口红','超短裙','乌冬面','冰淇淋','棒棒糖','长颈鹿','豆芽','发箍','发卡','发夹','发带','铃铛','小馒头','小笼包','小甜瓜','冬瓜','香菇','小兔子','含羞草','短靴','睫毛膏','小蘑菇','跳跳糖','小白菜','草莓','柠檬','月饼','百合','纸鹤','小天鹅','云朵','芒果','面包','海燕','小猫咪','龙猫','唇膏','鞋垫','羊','黑猫','白猫','万宝路','金毛','山水','音响');
        $tou_num=rand(0,331);
        $wei_num=rand(0,325);
        $nicheng=$nicheng_tou[$tou_num].$nicheng_wei[$wei_num];
        return $nicheng; //输出生成的昵称

    }
}   
